using System;
using System.Collections.Generic;
using System.Data;
using System.Net;
using System.Net.Mail;
using System.Runtime.InteropServices;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Specialized;


namespace MyWebPagesStarterKit.Utils
{
    
    /// <summary>
    /// Contains methods to send html emails.
    /// </summary>
    public class EmailSender
    {
        private static string exception = string.Empty;

        /// <summary>
        /// Sends an email with html.
        /// Calls the wanted Template from MailTemplates.
        /// </summary>
        /// <param name="status">Returning status of message. 0=sent, 1 = not sent</param>
        /// <param name="emailTo">The email address to send this email to</param>
        /// <param name="uniqueName">The unique title of template</param>
        /// <param name="replacements">Dictonary of replacements</param>
        public EmailSender(out int status, string emailTo, string uniqueName, Dictionary<string,string> replacements)
        {
            SendEmail(out status, emailTo, uniqueName, replacements);
        }

        private void SendEmail(out int status, string emailTo, string uniqueName, Dictionary<string, string> replacements)
        {
            WebSite instance = WebSite.GetInstance();
            MailDefinition definition = new MailDefinition();
            DataRow entriesFromKey = MailTemplate.GetInstance().GetRowFromTitle(uniqueName);

            if (entriesFromKey == null)
            {
                status = 1;
                return;
            }

            //Update fields from replacements
            string r = string.Empty;
            replacements.Add("<%EmailTo%>", emailTo);
            foreach (string key in replacements.Keys)
                r += key+"\n";
 
            entriesFromKey["Description"] = r;
            MailTemplate m = MailTemplate.GetInstance();
            m.Entries.AcceptChanges();
            m.SaveData();
            //End update

            string path = string.Format("~/App_Data/Templates/{0}/Mail/{1}.config", WebSite.GetInstance().Theme, Convert.ToString(entriesFromKey["TitleUnique"]));
            path = HttpContext.Current.Server.MapPath(path);
            definition.BodyFileName = path;
            definition.From = emailTo;
            definition.Subject = Convert.ToString(entriesFromKey["Subject"]);
            definition.IsBodyHtml = true;
            
            try
            {
                MailMessage message = definition.CreateMailMessage(emailTo, replacements, new LiteralControl());
                message.From = new MailAddress(instance.MailSenderAddress);
                SmtpClient client = new SmtpClient(instance.SmtpServer);
                client.UseDefaultCredentials = false;
                if (!string.IsNullOrEmpty(instance.SmtpPassword))
                {
                    client.Credentials = new NetworkCredential(instance.SmtpUser, instance.SmtpPassword, instance.SmtpServer);
                }
                client.Send(message);
                status = 0;
            }
            catch(Exception ex)
            {
                exception = ex.ToString();
                status = 1;
            }
        }


        /// <summary>
        /// Current status of a message
        /// </summary>
        /// <param name="status">The status of a message</param>
        /// <returns>String of current message</returns>
        public static string StatusMessage(int status)
        {
            switch (status)
            {
                case 0:
                    return "Message is sent";

                case 1:
                    return "Something went wrong while sending your email.<br/>";
            }
            //Default
            return "Something went wrong while sending your email.";
        }
    }
}

